package com.css.fxfzdpzs.modules.fxpg.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdpzs.modules.dzzh.entity.first.DzzhEarthquakeDisasterNum;
import com.css.fxfzdpzs.modules.dzzh.entity.first.DzzhProvinceDisasterNum;
import com.css.fxfzdpzs.modules.dzzh.entity.second.DpzsVO;
import com.css.fxfzdpzs.modules.fxpg.entity.*;
import com.css.fxfzdpzs.modules.fxpg.repository.FxpgRepository;
import com.css.fxfzdpzs.modules.fxpg.service.FxpgService;
import com.css.fxfzdpzs.modules.fxpg.vo.BuildingVO;
import com.css.fxfzdpzs.modules.fxpg.vo.HouseVo;
import com.css.fxfzdpzs.modules.fxpg.vo.LevelProVo;
import com.css.fxfzdpzs.modules.xczh.entity.first.DisasterVisitsCount;
import com.css.fxfzdpzs.modules.xczh.entity.second.XcResultDate;
import com.css.fxfzdpzs.modules.xczh.repository.XczhRepository;
import com.css.fxfzdpzs.util.PlatformObjectUtils;
import com.css.fxfzdpzs.util.RestTemplateUtil;
import com.css.fxfzdpzs.util.UUIDGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FxpgServiceImpl implements FxpgService {
    @Autowired
    private FxpgRepository fxpgRepository;
    @Autowired
    private XczhRepository xczhRepository;

    Properties configGroup = PropsHelper.loadProps("slw-config.properties");

    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Override
    public ActivityFaultData getActivityFaultData() {
        return fxpgRepository.getActivityFaultData();
    }

    @Override
    public Double[] getNationwideRiskData() {
        List<NationwideRiskData> dataList = fxpgRepository.getNationwideRiskData();
        if (dataList.size()==0){
            Double[] doubles = {0.0, 0.0, 0.0, 0.0};
            return doubles;
        }
        Double[] doubles = {dataList.get(0).getNumber(), dataList.get(1).getNumber(), dataList.get(2).getNumber(), dataList.get(3).getNumber()};
        return doubles;
    }

    @Override
    public Map<String, Object> getBodyData() {
        List<DisasterBodyData> dataList = fxpgRepository.getBodyData();
        //按房屋用途分类HouseUse
        List<HouseVo> list1 = new ArrayList<>();
        Map<String, List<DisasterBodyData>> map1 = dataList.stream().collect(Collectors.groupingBy(DisasterBodyData::getHouseUse));
        for (Map.Entry<String, List<DisasterBodyData>> entry : map1.entrySet()) {
            HouseVo houseVo = new HouseVo(entry.getKey(), entry.getValue().size());
            list1.add(houseVo);
        }
        list1 = list1.stream().sorted(Comparator.comparing(s -> Integer.valueOf(s.getType()))).collect(Collectors.toList());
        //按结构类型分类
        List<HouseVo> list2 = new ArrayList<>();
        Map<String, List<DisasterBodyData>> map2 = dataList.stream().collect(Collectors.groupingBy(DisasterBodyData::getStructureType));
        for (Map.Entry<String, List<DisasterBodyData>> entry : map2.entrySet()) {
            HouseVo houseVo = new HouseVo(entry.getKey(), entry.getValue().size());
            list2.add(houseVo);
        }
        list2 = list2.stream().sorted(Comparator.comparing(s -> Integer.valueOf(s.getType()))).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("houseUse", list1);
        map.put("structureType", list2);
        return map;
    }


    @Override
    public List<KeynoteTargetData> getKeynoteTargetData() {
        List<KeynoteTargetData> list = fxpgRepository.getKeynoteTargetData();
        List<KeynoteTargetData> vos = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 2; j++) {
                KeynoteTargetData vo = new KeynoteTargetData(String.valueOf(i), String.valueOf(j), 0);
                vos.add(vo);
            }
        }
        for (KeynoteTargetData vo : vos) {
            for (KeynoteTargetData dataVo : list) {
                if (dataVo.getType().equals(vo.getType()) && dataVo.getLevel().equals(vo.getLevel())) {
                    vo.setCount(dataVo.getCount());
                    break;
                }
            }
        }
        return vos;
    }


    @Override
    public Map<String, Object> getRiskEstimateData(String estimate0bj,String condition,String assessType) {
        List<RiskEstimateData> dataList = fxpgRepository.getRiskEstimateData(estimate0bj,condition,assessType);
        List<RiskEstimateData> ryss = dataList.stream().sorted(Comparator.comparing(RiskEstimateData::getInjured).reversed()).limit(5).collect(Collectors.toList());
        List<RiskEstimateData> rysw = dataList.stream().sorted(Comparator.comparing(RiskEstimateData::getDeath).reversed()).limit(5).collect(Collectors.toList());
        List<RiskEstimateData> jjss = dataList.stream().sorted(Comparator.comparing(RiskEstimateData::getEconomyLoss).reversed()).limit(5).collect(Collectors.toList());
        List<RiskEstimateData> dtfx = dataList.stream().sorted(Comparator.comparing(RiskEstimateData::getRiskValue).reversed()).limit(5).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("ryss", ryss);
        map.put("rysw", rysw);
        map.put("jjss", jjss);
        map.put("dtfx", dtfx);
        return map;
    }

    @Override
    public List<LevelProVo> getRiskPlanData(String assessType,String estimate0bj,String condition) {
        List<RiskPlanData> list = fxpgRepository.getRiskPlanData(assessType,estimate0bj,condition);
        //List<RiskPlanData> list = fxpgRepository.getRiskPlanData(assessType,estimate0bj,condition);
        List<LevelProVo> vos = new ArrayList<LevelProVo>();
        Map<String, List<RiskPlanData>> listMap = list.stream().collect(Collectors.groupingBy(RiskPlanData::getLevel));
        for (Map.Entry<String, List<RiskPlanData>> entry : listMap.entrySet()) {
            BigDecimal bigDecimal = BigDecimal.valueOf(entry.getValue().size()).divide(BigDecimal.valueOf(list.size()), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            LevelProVo vo = new LevelProVo();
            vo.setLevel(entry.getKey());
            vo.setProportion(bigDecimal.doubleValue());
            vos.add(vo);
        }
        Map<String, List<LevelProVo>> map = vos.stream().collect(Collectors.groupingBy(LevelProVo::getLevel));
        List<LevelProVo> levelProVos = addZeroLevel(map);
        if(levelProVos.size()>0){
            vos.addAll(levelProVos);
        }
        vos.sort((o1, o2) -> {
            Integer i1 = Integer.parseInt(o1.getLevel());
            Integer i2 = Integer.parseInt(o2.getLevel());
            return i2.compareTo(i1);
        });
        return vos;
    }

    @Override
    public Map<String, Object> getVisitNum(String system) {
        List<DisasterVisitsCount> list = xczhRepository.getVisitNum(system);
        Map<String, Object> map = new HashMap<>();
        int todaySum = list.stream().mapToInt(DisasterVisitsCount::getTodayVisitNum).sum();
        int accumulateSum = list.stream().mapToInt(DisasterVisitsCount::getAccumulateVisitNum).sum();
        map.put("todaySum", todaySum);
        map.put("accumulateSum", accumulateSum);
        return map;
    }

    @Override
    public List<DisasterOverview> getDisasterOverview(String system) {
        List<DisasterOverview> list =  fxpgRepository.getDisasterOverview(system);

        List<String> collect = list.stream().map(DisasterOverview::getDisasterType).collect(Collectors.toList());
        if((PlatformObjectUtils.isNotEmpty(collect) && collect.size()<3) || (PlatformObjectUtils.isEmpty(list) || list.size()==0)){
            if(!collect.contains("0")){
                DisasterOverview disasterOverview = new DisasterOverview();
                disasterOverview.setId(UUIDGenerator.getUUID());
                disasterOverview.setDisasterType("0");
                disasterOverview.setSystem("0");
                disasterOverview.setPoleHighProportion(0.0);
                disasterOverview.setHighProportion(0.0);
                disasterOverview.setCentreProportion(0.0);
                disasterOverview.setLowProportion(0.0);
                disasterOverview.setPoleLowProportion(0.0);
                list.add(disasterOverview);
            }
            if(!collect.contains("1")){
                DisasterOverview disasterOverview = new DisasterOverview();
                disasterOverview.setId(UUIDGenerator.getUUID());
                disasterOverview.setDisasterType("1");
                disasterOverview.setSystem("0");
                disasterOverview.setPoleHighProportion(0.0);
                disasterOverview.setHighProportion(0.0);
                disasterOverview.setCentreProportion(0.0);
                disasterOverview.setLowProportion(0.0);
                disasterOverview.setPoleLowProportion(0.0);
                list.add(disasterOverview);
            }
            if(!collect.contains("2")){
                DisasterOverview disasterOverview = new DisasterOverview();
                disasterOverview.setId(UUIDGenerator.getUUID());
                disasterOverview.setDisasterType("1");
                disasterOverview.setSystem("0");
                disasterOverview.setYesProportion(0.0);
                disasterOverview.setNoProportion(0.0);
                list.add(disasterOverview);
            }
        }
        return list;
    }


    @Override
    public Map<String, List<DisasterData>> getDisasterBodyData() {
        //largeScreen/getBuildingCategoryStatistics?code=0 调用接口
//        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
//        String url = configGroup.getProperty("fxqhRestUrl") + "largeScreen/getBuildingCategoryStatistics?code=0";
//        Map<String, Object> paramMap = new HashMap<>();
//        //   paramMap.put("code", dataVersion);
//        ResponseEntity<String> cchResponseEntity = restTemplateUtil.sendHttpRequestPj(url, paramMap);
//        List<DisasterData> list = JSONObject.parseArray(cchResponseEntity.getBody(), DisasterData.class);

        //   ResponseEntity<String> poResponseEntity = restTemplateUtil.sendHttpRequestPj(poUrl, paramMap1);
        //  JcPopulation jcPopulation = JSONObject.parseObject(poResponseEntity.getBody(), JcPopulation.class);
        List<DisasterData> list = fxpgRepository.getDisasterBodyData();
        Map<String, List<DisasterData>> map = list.stream().collect(Collectors.groupingBy(DisasterData::getCategory));
        List<DisasterData> disasterData = map.get("1");
        Map<String, List<DisasterData>> typeMap = disasterData.stream().collect(Collectors.groupingBy(DisasterData::getType));
        for(int i=1;i<=13;i++){
            List<DisasterData> disasterBodyData = typeMap.get(i+"");
            if(PlatformObjectUtils.isEmpty(disasterBodyData) || disasterBodyData.size()==0){
                DisasterData data = new DisasterData();
                data.setId(UUIDGenerator.getUUID());
                data.setCategory("1");
                data.setType(i+"");
                data.setHouseNum(0.0);
                data.setArea(0.0);
                disasterData.add(data);
                map.put("1",disasterData);
            }
        }
        for (Map.Entry<String, List<DisasterData>> entry : map.entrySet()) {
            List<DisasterData> collect = entry.getValue().stream().sorted(Comparator.comparing(s -> Integer.valueOf(s.getType()))).collect(Collectors.toList());
            entry.setValue(collect);
        }
        return map;
    }

    private List<LevelProVo> addZeroLevel(Map<String, List<LevelProVo>> map ){
        List<LevelProVo> list = new ArrayList<>();
        if(PlatformObjectUtils.isEmpty(map.get("1"))){
            LevelProVo vo = new LevelProVo();
            vo.setLevel("1");
            vo.setProportion(0.0);
            list.add(vo);
        }
        if(PlatformObjectUtils.isEmpty(map.get("2"))){
            LevelProVo vo = new LevelProVo();
            vo.setLevel("2");
            vo.setProportion(0.0);
            list.add(vo);
        }
        if(PlatformObjectUtils.isEmpty(map.get("3"))){
            LevelProVo vo = new LevelProVo();
            vo.setLevel("3");
            vo.setProportion(0.0);
            list.add(vo);
        }
        if(PlatformObjectUtils.isEmpty(map.get("4"))){
            LevelProVo vo = new LevelProVo();
            vo.setLevel("4");
            vo.setProportion(0.0);
            list.add(vo);
        }
        if(PlatformObjectUtils.isEmpty(map.get("5"))){
            LevelProVo vo = new LevelProVo();
            vo.setLevel("5");
            vo.setProportion(0.0);
            list.add(vo);
        }
        return list;
    }
    @Override
    public List<RiskMapData> getMapRiskData(String type) {
        return fxpgRepository.getMapRiskData(type);
    }

    @Override
    public void remoteVisitNum() {
        //访问量
        final String visitUrl = configGroup.getProperty("baseUrl") + "/slog_dzj/getLogs";
        //访问量
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequestPj(visitUrl, new HashMap<>());
        if(responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            JSONObject js = (JSONObject) JSONObject.parse(responseEntity.getBody());
            JSONArray resultArr = (JSONArray) js.get("result");
            List<Visit> visitList = JSON.parseArray(resultArr.toJSONString(), Visit.class);
            if(visitList.size()>0){
                fxpgRepository.deleteVisitData();
                fxpgRepository.saveVisitData(visitList);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fxpgData() {
        ObjectMapper objectMapper = new ObjectMapper();

        //大区划全国危险性等级区划接口地址
        final String sjxtDamageUrl = configGroup.getProperty("sjxtRestUrl") + "datacenter/jcDangerousLevelm/getAll";
        //大区划全国建筑物分类统计接口地址
        final String buildingCategoryStaticUrl = configGroup.getProperty("sjxtRestUrl") + "largeScreen/getBuildingCategoryStatistics";
        //全国重点目标数据接口地址
        final String keyNoteUrl = configGroup.getProperty("fxqhRestUrl") + "largeScreen/getKeyNote";
        //全国地震灾害风险评估
        final String disasterRiskAssessUrl = configGroup.getProperty("fxqhRestUrl") + "largeScreen/getEarthquakeDisasterRiskAssessment?code=0&type=0";
        //全国地震灾害风险区划
        final String riskZonationUrl = configGroup.getProperty("fxqhRestUrl") + "largeScreen/getRiskZonation";
        //全国地震地质灾害概况   dzzhRestUrl
        final String dzzhDisasterUrl = configGroup.getProperty("dzzhRestUrl") + "softSoil/getCountAreaResult";

        Map<String, Object> paramMap = new HashMap<>();
        //   paramMap.put("code", dataVersion);
        //调用大区划接口 同步到大屏数据库
        //大区划全国危险性等级区划
        ResponseEntity<JSONObject> cchResponseEntity = restTemplateUtil.sendHttpRequestjS(sjxtDamageUrl, paramMap);
        if(cchResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()){
            Map<String,Object> data =(Map<String,Object>) cchResponseEntity.getBody().get("data");
            List<LinkedHashMap> mapList = (List<LinkedHashMap>) data.get("riskMap");
            if(PlatformObjectUtils.isNotEmpty(mapList) && mapList.size()>0){
                //先删除地图全国危险性等级区划数据
                fxpgRepository.deleteMapRiskData();
                List<RiskMapData> riskMapDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : mapList) {
                    RiskMapData riskMapData = objectMapper.convertValue(linkedHashMap, RiskMapData.class);
                    riskMapDataList.add(riskMapData);
                }
                fxpgRepository.saveMapRiskData(riskMapDataList);
            }
            List<LinkedHashMap> nationwideList = (List<LinkedHashMap>) data.get("nationwide");
            if(PlatformObjectUtils.isNotEmpty(nationwideList) && nationwideList.size()>0){
                //先删除全国危险性等级区划折线图数据
                fxpgRepository.deleteNationwideRiskData();
                List<NationwideRiskData> nationwideRiskDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : nationwideList) {
                    NationwideRiskData nationwideRiskData = objectMapper.convertValue(linkedHashMap, NationwideRiskData.class);
                    nationwideRiskDataList.add(nationwideRiskData);
                }
                fxpgRepository.saveNationwideRiskData(nationwideRiskDataList);
            }
            System.out.println("111");
        }
        //全国建筑物分类统计
        ResponseEntity<JSONObject> categoryStaticResponseEntity = restTemplateUtil.sendHttpRequestjS(buildingCategoryStaticUrl, paramMap);
        if(categoryStaticResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()){
            Map<String,Object> data =(Map<String,Object>) categoryStaticResponseEntity.getBody().get("data");
            List<LinkedHashMap> bcsList = (List<LinkedHashMap>) data.get("result");
            if(PlatformObjectUtils.isNotEmpty(bcsList) && bcsList.size()>0){
                //先删除地图全国危险性等级区划数据 fxpg_disaster_data
                fxpgRepository.delDisasterData();
                List<DisasterData> disasterDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : bcsList) {
                    BuildingVO buildingVO = objectMapper.convertValue(linkedHashMap, BuildingVO.class);
                    DisasterData disasterData = new DisasterData();
                    BeanUtils.copyProperties(buildingVO,disasterData);
                    disasterData.setHouseNum(PlatformObjectUtils.isNotEmpty(buildingVO.getHouseNum())?buildingVO.getHouseNum().doubleValue():0.0);
                    disasterData.setArea(PlatformObjectUtils.isNotEmpty(buildingVO.getArea())?buildingVO.getArea().divide(new BigDecimal(100000000)).doubleValue():0.0);
                    disasterDataList.add(disasterData);
                }
                fxpgRepository.saveDisasterData(disasterDataList);
            }
            List<LinkedHashMap> dataList = (List<LinkedHashMap>) data.get("dataList");
            if(PlatformObjectUtils.isNotEmpty(dataList) && dataList.size()>0){
                //先删除地图全国危险性等级区划数据 fxpg_disaster_data
                fxpgRepository.delDisasterBodyData();
                List<DisasterBodyData> disasterBodyDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : dataList) {
                    DisasterBodyData disasterBodyData = objectMapper.convertValue(linkedHashMap, DisasterBodyData.class);
                    disasterBodyData.setGeomText(disasterBodyData.getGeom());
                    disasterBodyDataList.add(disasterBodyData);
                }
                fxpgRepository.saveDisasterBodyData(disasterBodyDataList);
            }
        }
        //全国重点目标数据
        ResponseEntity<JSONObject> keyNoteResponseEntity = restTemplateUtil.sendHttpRequestjS(keyNoteUrl, paramMap);
        if(keyNoteResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()){
            Map<String,Object> data =(Map<String,Object>) keyNoteResponseEntity.getBody().get("data");
            List<LinkedHashMap> knList = (List<LinkedHashMap>) data.get("result");
            if(PlatformObjectUtils.isNotEmpty(knList) && knList.size()>0){
                List<KeynoteTargetData> keynoteTargetDataList = new ArrayList<>(knList.size());
                List<KeynoteData> keynoteMapDataList = new ArrayList<>();
                List<KeynoteData> keynoteDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : knList) {
                    KeynoteData keynoteData = objectMapper.convertValue(linkedHashMap, KeynoteData.class);
                    keynoteDataList.add(keynoteData);
                }
                if(keynoteDataList.size()>0){
                    for (KeynoteData keynoteData : keynoteDataList) {
                        keynoteData.setKeynoteName(getKeyNoteCodeByName(keynoteData.getKeynoteName())).setLevel(getLevelCodeByName(keynoteData.getLevel()));
                        keynoteMapDataList.add(keynoteData);
                    }
                    //<类型，<等级，集合>>
                    Map<String, Map<String, List<KeynoteData>>> knMap = keynoteDataList.stream().collect(Collectors.groupingBy(KeynoteData::getKeynoteName, Collectors
                            .groupingBy(KeynoteData::getLevel)));
                    knMap.forEach((k,v)->{
                        v.forEach((k1,v1)->{
                            //0学校 1医院 2生命线 3重大工程 4重点目标
                            KeynoteTargetData keynoteTargetData = new KeynoteTargetData();
                            keynoteTargetData.setId(UUIDGenerator.getUUID()).setType(k).setLevel(k1).setCount(v1.size());
                            keynoteTargetDataList.add(keynoteTargetData);
                        });
                    });
                }
                if(keynoteTargetDataList.size()>0){
                    fxpgRepository.deleteKeyNoteTargetData();
                    fxpgRepository.saveKeynoteTargetData(keynoteTargetDataList);
                }
                if(keynoteMapDataList.size()>0){
                    fxpgRepository.deleteKeynoteMapData();
                    fxpgRepository.saveKeynoteMapData(keynoteMapDataList);
                }

            }
        }
        //全国地震灾害风险评估
        ResponseEntity<JSONObject> riskAssessResponseEntity = restTemplateUtil.sendHttpRequestjS(disasterRiskAssessUrl, paramMap);
        if(riskAssessResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            Map<String, Object> data = (Map<String, Object>) riskAssessResponseEntity.getBody().get("data");
            List<LinkedHashMap> riskAssessList = (List<LinkedHashMap>) data.get("result");
            if (PlatformObjectUtils.isNotEmpty(riskAssessList) && riskAssessList.size() > 0) {
                 List<RiskEstimateData> riskEstimateDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : riskAssessList) {
                    RiskEstimateData riskEstimateData = objectMapper.convertValue(linkedHashMap, RiskEstimateData.class);
                    riskEstimateDataList.add(riskEstimateData);
                }
                if(riskEstimateDataList.size()>0){
                    fxpgRepository.delRiskEstimateData();
                    fxpgRepository.saveRiskEstimateData(riskEstimateDataList);
                }
            }
        }
        //全国地震灾害风险区划 riskZonationUrl
        ResponseEntity<JSONObject> riskZonationResponseEntity = restTemplateUtil.sendHttpRequestjS(riskZonationUrl, paramMap);
        if(riskZonationResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            Map<String, Object> data = (Map<String, Object>) riskZonationResponseEntity.getBody().get("data");
            List<LinkedHashMap> riskZonationList = (List<LinkedHashMap>) data.get("result");
            if (PlatformObjectUtils.isNotEmpty(riskZonationList) && riskZonationList.size() > 0) {
                List<AssessQh> riskEstimateDataList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : riskZonationList) {
                    AssessQh assessQh = objectMapper.convertValue(linkedHashMap, AssessQh.class);
                    assessQh.setAssessType(addAndGet(assessQh.getAssessType()));
                    assessQh.setEstimateObj(addAndGet(assessQh.getEstimateObj()));
                    assessQh.setCondition(numToStr(assessQh.getCondition()));
                    assessQh.setQhLevel(getMap().get(assessQh.getQhLevel()));
                    riskEstimateDataList.add(assessQh);
                }
                if (riskEstimateDataList.size()>0) {
                    fxpgRepository.deleteRiskEstimateData();
                    fxpgRepository.saveAssessQh(riskEstimateDataList);
                }
            }
        }
        ResponseEntity<JSONObject> dzzhDisasterResponseEntity = restTemplateUtil.sendHttpRequestjS(dzzhDisasterUrl, paramMap);
        if(dzzhDisasterResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            Map<String, Object> data = (Map<String, Object>) dzzhDisasterResponseEntity.getBody().get("data");
            List<LinkedHashMap> dzzhDisasterList = (List<LinkedHashMap>) data.get("result");
            if (PlatformObjectUtils.isNotEmpty(dzzhDisasterList) && dzzhDisasterList.size() > 0) {
                List<CountAreaResult> countAreaResultList = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : dzzhDisasterList) {
                    CountAreaResult countAreaResult = objectMapper.convertValue(linkedHashMap, CountAreaResult.class);
                    countAreaResultList.add(countAreaResult);
                }
                //按照类型分类 //模型类型：地震滑坡-逻辑斯蒂模型；砂土液化-层次分析法；软土震陷
                Map<String, List<CountAreaResult>> typeMap = countAreaResultList.stream().collect(Collectors.groupingBy(CountAreaResult::getModelType));
                List<DisasterOverview> resultList = new ArrayList<>();
                typeMap.forEach((k,v)->{
                    DisasterOverview disasterOverview = new DisasterOverview();
                    disasterOverview.setId(UUIDGenerator.getUUID());
                    String disasterType = getDisasterType(k);
                    disasterOverview.setDisasterType(disasterType);
                    disasterOverview.setSystem("0");
                    //按占比分组
                    Map<String, List<CountAreaResult>> ratioMap = v.stream().collect(Collectors.groupingBy(CountAreaResult::getGridvalue));
                    //k是模型类型  v是对应的数据
                    if("地震滑坡-逻辑斯蒂模型".equals(k) || "砂土液化-层次分析法".equals(k)){
                        ratioMap.forEach((k1,v1)->{
                            //各个等级危险性面积
                            BigDecimal area = v1.stream().map(CountAreaResult::getArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal totalArea = v1.stream().map(CountAreaResult::getTotalArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal percent = area.divide(totalArea,2,RoundingMode.HALF_DOWN).multiply(new BigDecimal(100));
                            if("1".equals(k1)){
                                disasterOverview.setPoleHighProportion(percent.doubleValue());
                            }else  if("2".equals(k1)){
                                disasterOverview.setHighProportion(percent.doubleValue());
                            }else  if("3".equals(k1)){
                                disasterOverview.setCentreProportion(percent.doubleValue());
                            }else  if("4".equals(k1)){
                                disasterOverview.setLowProportion(percent.doubleValue());
                            }else  if("5".equals(k1)){
                                disasterOverview.setPoleLowProportion(percent.doubleValue());
                            }

                        });
                    }else{
                        ratioMap.forEach((k1,v1)->{
                            //各个等级危险性面积
                            BigDecimal area = v1.stream().map(CountAreaResult::getArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal totalArea = v1.stream().map(CountAreaResult::getTotalArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal percent = area.divide(totalArea,2, RoundingMode.HALF_DOWN).multiply(new BigDecimal(100));
                            if("0".equals(k1)){
                                disasterOverview.setNoProportion(percent.doubleValue());
                            }else  if("1".equals(k1)){
                                disasterOverview.setYesProportion(percent.doubleValue());
                            }
                        });
                    }
                    resultList.add(disasterOverview);
                });
                if(resultList.size()>0){
                    fxpgRepository.delDisasterOverViewData();
                    fxpgRepository.saveDisasterOverViewData(resultList);
                }
            }
        }

//        Map<String,Object> data =(Map<String,Object>) cchResponseEntity.getBody().get("data");
//        ResponseEntity<String> cchResponseEntityB = restTemplateUtil.sendHttpRequestPj(urlB, paramMap);
//        List<DisasterData> vo = JSONObject.parseArray(cchResponseEntity.getBody().toJSONString(), DisasterData.class);
//
//        fxpgRepository.delDisasterData();
//        fxpgRepository.saveDisasterData(vo);
//        List<RiskEstimateData> voB = JSONObject.parseArray(cchResponseEntityB.getBody(), RiskEstimateData.class);
//        fxpgRepository.delRiskEstimateData();
//        fxpgRepository.saveRiskEstimateData(voB);


    }
    private Map<String,String> getMap(){
        Map<String,String> map = new HashMap<>();
        map.put("I","1");
        map.put("II","2");
        map.put("III","3");
        map.put("IV","4");
        map.put("V","5");
        return map;
    }
    private String addAndGet(String assessType){
        return (Integer.parseInt(assessType)+1)+"";
    }
    private String numToStr(String intensity){
        String value = "";
        switch (intensity){
            case "ld1": value = "1";
            case "ld2": value = "2";
            case "ld3": value = "3";
            case "ld4": value = "4";
            case "ld5": value = "5";
            default:
        }
        return value;
    }

    private String getDisasterType(String modelType){
        String disasterType = "";
        switch (modelType){
            case "地震滑坡-逻辑斯蒂模型" :
                disasterType = "0";
                break;
            case "砂土液化-层次分析法" :
                disasterType = "1";
                break;
            case "软土震陷" :
                disasterType = "2";
                break;
            default:
        }
        return disasterType;
    }

    /**
     * 根据重点目标的名称获取对应的code 0学校 1医院 2生命线 3重大工程 4重点目标
     */
    private String getKeyNoteCodeByName(String keyNoteName){
        String keyNoteCode = "";
        switch (keyNoteName){
            case "学校" :
                keyNoteCode = "0";
                break;
            case "医院" :
                keyNoteCode = "1";
                break;
            case "生命线" :
                keyNoteCode = "2";
                break;
            case "重大工程" :
                keyNoteCode = "3";
                break;
            case "重点目标" :
                keyNoteCode = "4";
                break;
            default:
        }
        return keyNoteCode;
    }

    private String getLevelCodeByName(String level){
        String levelCode = "";
        switch (level){
            case "Ⅰ" :
                levelCode = "1";
                break;
            case "Ⅱ" :
                levelCode = "2";
                break;
            case "Ⅲ" :
                levelCode = "3";
                break;
            case "Ⅳ" :
                levelCode = "4";
                break;
            case "Ⅴ" :
                levelCode = "5";
                break;
            default:
        }
        return levelCode;
    }


}